//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Web;
using System.Web.UI;
using CommunityServer.Components;
using CommunityServer.Discussions.Components;

namespace CommunityServer.Discussions.Controls {

	public class PageTitle : LiteralControl {

		// Used to set the title of the page the control is rendered on
		public virtual String Title {
			get {
				Object state = ViewState["Title"];
				if ( state != null ) {
					return (String)state;
				}
				return CSContext.Current.SiteSettings.SiteName;
			}
			set {
				ViewState["Title"] = value;
			}
		}

		[
		System.ComponentModel.DefaultValue( true ),
		]
		public virtual Boolean DisplayTitle {
			get {
				Object state = ViewState["DisplayTitle"];
				if ( state != null ) {
					return (Boolean)state;
				}
				return true;
			}
			set {
				ViewState["DisplayTitle"] = value;
			}
		}

		
		protected override void Render(HtmlTextWriter writer) {

			if (DisplayTitle) {

			    CSContext csContext = CSContext.Current;

				Forum forum = null;
			    ForumPost post = null;
				User user = null;

				string seperator = " - ";

				// Get the user if available we'll personalize the title
				//
				if (Context.Request.IsAuthenticated) {
					user = csContext.User;
				}


				// the following are a list of checks 
           
				// Do we have a ForumID?
				//
				if (csContext.SectionID > 0) {
					forum = Forums.GetForum(csContext.SectionID);

					if( forum != null && forum.Name != null ) {
						Title = forum.Name + seperator + Title;
					}
				}

				// Do we have a PostID?
				//
				if (csContext.PostID > 0) {
					post = Posts.GetPost(csContext.PostID, csContext.User.UserID);

					if( post != null && post.Subject != null ) {
						Title = post.Subject + seperator + Title;
					}
				}

				if (user != null)
					base.Text = "<title>" + Title + " (" + user.Username + ")</title>\n";
				else
					base.Text = "<title>" + Title + "</title>\n";
			}

			base.Render (writer);
		}


	}
}
